using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MCGameEngine.Sprite_Layer
{
    public class Sprite
    {
        private float step=0;
        private Rectangle current;
        private int n_frame;
        private Texture2D texture;

        public static int frame_per_second = 36;

        public Vector2 Position;
        public Color Filter;

        private List<Rectangle> frames;

        private bool is_playing;
        private int play_start;
        private int play_end;

        public Sprite(Texture2D texture, int n_frame)
        {
            this.n_frame = n_frame;
            this.texture = texture;
            Position = new Vector2(0, 0);
            Filter = Color.White;

            frames = new List<Rectangle>();

            int sizestep=(int)Math.Sqrt(n_frame);

            Point start=Point.Zero;
            Point end = new Point(texture.Width / sizestep, texture.Height / sizestep);

            for (int i = 0; i < sizestep; i++)
            {
                for (int j = 0; j < sizestep; j++)
                {
                    Rectangle r = new Rectangle(start.X, start.Y, end.X, end.Y);
                    r.X = end.X * i;
                    r.Y = end.Y * j;
                    frames.Add(r);
                }
            }

            is_playing = false;
            play_start = 0;
            play_end = frames.Count - 1;
            
            current = frames[0];
        }

        public Texture2D Frames
        {
            get
            {
                return texture;
            }
        }

        public Rectangle CurrentFrame
        {
            get
            {
                return current;
            }
        }

        public void Play()
        {
            is_playing=true;
        }

        public void Pause()
        {
            is_playing = false;
        }

        public void Play(int start,int end)
        {
            play_start=start;
            play_end=end;
        }

        public void Update(float elapsed)
        {
            if (elapsed != 0)
            {
                if (is_playing)
                {
                    step = step + elapsed * frame_per_second;

                    if (step >= frames.Count || step >= play_end)
                    {
                        step = play_start;
                    }

                    current = frames[(int)step];
                }
            }
        }
    }
}
